package cn.itcast.blog.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.itcast.blog.domain.AjaxResponse;
import cn.itcast.blog.domain.Post;
/**
 * 使用反射整合代码
 * @author 16604
 *
 */
public class BaseServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//根据请求路径，调用对应的方法
		//获取请求路径，获取最后一部分，得到方法名
		String uri = req.getRequestURI();
		int index = uri.lastIndexOf("/");
		String methodName = uri.substring(index+1);
		//根据方法名称，调用响应的方法,后面是class类型的参数
		try {
			Method declaredMethod = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			
			declaredMethod.invoke(this, req,resp);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	protected <E> void writeListResponse(HttpServletResponse resp,List<E> data) throws IOException {
		
		AjaxResponse<E> ajaxPostResponse = new AjaxResponse<>();
		
		ajaxPostResponse.setCode(0);
		ajaxPostResponse.setCount(100);
		ajaxPostResponse.setMsg("");
		ajaxPostResponse.setData(data);
		
		String string = JSON.toJSONString(ajaxPostResponse);
		
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(string);
		
		
	}
}
